<!-- pages/ai-robot.vue -->
<template>
  <div class="news-wrap">
    <Navbar />
    <div class="chat-container">
      <div class="chat-list">
        <!-- 聊天列表项 -->
        <div v-for="(message, index) in messages" :key="index" class="chat-item" :class="{
          'chat-item-user': message.user,
          'chat-item-bot': !message.user,
          processing: message.processing,
        }">
          <div v-if="!message.user" class="chat-avatar bot-avatar">
            <img src="@/assets/images/bot-avatar.png" alt="Avatar" class="avatar" />
          </div>
          <div class="chat-bubble" :class="{
            'bubble-user': message.user,
            'bubble-bot': !message.user,
          }">
            <div v-if="message.processing" class="processing-text">
              {{ message.text }}
            </div>
            <span v-else-if="message.type === 'text'" v-html="message.text"></span>
            <div v-else>
              <UTable :data="message.tableData" class="flex-1 whitespace-nowrap table-all">
                <template #caption="{ text }">
                  <div class="flex items-center">
                    <div class="text-[14px] font-bold">{{ text }}</div>
                  </div>
                </template>
              </UTable>
            </div>
          </div>
          <div v-if="message.user" class="chat-avatar user-avatar">
            <img src="@/assets/images/user-avatar.png" alt="Avatar" class="avatar w-[36px]" />
          </div>
        </div>
      </div>
      <div class="input-container">
        <textarea v-model="inputValue" @keyup.enter="handleInputSubmit" class="input-field" placeholder="给幻引小助手发送消息……"
          :disabled="isSending"></textarea>
        <button @click="handleInputSubmit" :class="['input-button', { active: inputValue.trim() }]"
          :disabled="isSending">
          <svg class="input-icon" width="19.437012" height="19.452942" viewBox="0 0 19.437 19.4529" fill="none"
            xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
            <defs />
            <path id="Vector"
              d="M19.32 1.41C19.47 1.82 19.47 2.27 19.33 2.68L14.23 18.02C13.85 19.1 12.69 19.69 11.62 19.35C11.11 19.17 10.7 18.82 10.45 18.35L7.96 13.62C7.73 13.19 7.81 12.65 8.16 12.3L12.07 8.39C12.36 8.1 12.36 7.64 12.08 7.34C11.79 7.05 11.32 7.05 11.02 7.34L7.11 11.25C6.76 11.6 6.22 11.68 5.79 11.45L1.06 8.93C0.07 8.4 -0.3 7.16 0.25 6.16C0.49 5.69 0.91 5.34 1.42 5.18L16.75 0.1C17.83 -0.25 18.98 0.33 19.32 1.41Z"
              fill="#FFFFFF" fill-opacity="1.000000" fill-rule="nonzero" />
          </svg>
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'

import { useState } from '#app'
import Navbar from '~/components/navbar.vue'
// 导入 userApi 实例
import userApi from '@/api/index';
const configs = useState('configs', () => [])
// 定义 emit
const emit = defineEmits(['update-footer-style'])

const selectedItem = ref('')
const inputValue = ref('')
const isSending = ref(false)

const getConfigItem = (name) => {
  return configs.value.length ? configs.value.filter(it => it.name === name)[0]?.value || "" : "";
}


const messages = ref([({ user: false, type: 'text', text: getConfigItem("welcome_tips") || '您好，我是智能机器人，很高兴为您服务', processing: false })])



onMounted(() => {
  // 触发事件
  emit('update-footer-style', '#f9fbff', '#9D9D9D')
  // 从 localStorage 读取
  selectedItem.value = localStorage.getItem('questions') || '';
  if (selectedItem.value.trim() && !isSending.value) {
    isSending.value = true // 锁定发送状态
    messages.value.push({ user: true, type: 'text', text: selectedItem.value })
    handleAskQuestions(selectedItem.value);
  }
})

const handleInputSubmit = () => {
  if (inputValue.value.trim() && !isSending.value) {
    isSending.value = true // 锁定发送状态
    messages.value.push({ user: true, type: 'text', text: inputValue.value })
    handleAskQuestions(inputValue.value);
  }
}


async function handleAskQuestions(text) {
  try {
    inputValue.value = ''
    selectedItem.value = '';
    localStorage.removeItem('questions');
    messages.value.push({ user: false, type: 'text', text: '处理中', processing: true })
    const response = await userApi.askQuestions(`data=${text}&session_id=1&endpoint_id=${localStorage.getItem('user_id')}`)

    if (response) {
      const res = JSON.parse(response);
      if (res.data.action_type === 'nlq' && res.data.action_text.indexOf("{") >= 0) {
        const action_text = JSON.parse(res.data.action_text);
        // console.log('handleAskQuestions successful:', action_text)
        if (action_text?.type === "table" && action_text.data?.length > 0) {
          // console.log(action_text.data)
          const lastMessageIndex = messages.value.length - 1
          messages.value[lastMessageIndex] = {
            user: false,
            type: 'table',
            tableData: action_text.data,
            text: action_text.title,
            processing: false,
          }
        }

      } else {
        const lastMessageIndex = messages.value.length - 1
        messages.value[lastMessageIndex] = {
          user: false,
          type: 'text',
          text: res.data.action_text,
          processing: false,
        }
      }
    }
    isSending.value = false // 解锁发送状态
    // 处理登录成功后的逻辑，例如保存 token
  } catch (error) {
    console.error('getNews failed:', error)
    // 处理登录失败后的逻辑
    isSending.value = false // 解锁发送状态
  }
}
</script>
<style scoped>
.news-wrap {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: calc(100vh - 110px);
  box-sizing: border-box;
  background: #f9fbff;
}

.chat-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
}

.chat-list {
  flex: 1;
  width: 1140px;
  margin-left: auto;
  margin-right: auto;
  margin-top: 120px;
  padding: 20px;
  overflow-y: auto;
}

.chat-item {
  display: flex;
  margin-bottom: 20px;
  align-items: flex-start;
}

.chat-avatar {
  width: 36px;
  height: 36px;
  margin-right: 10px;
  margin-left: 10px;
}

.chat-avatar.user-avatar {
  margin-right: 10px;
  margin-right: 10px;
}

.chat-avatar.bot-avatar {
  margin-right: 10px;
  margin-left: 10px;
}

.chat-avatar img {
  width: 100%;
  height: 100%;
  /* border-radius: 50%; */
  object-fit: cover;
}

.chat-bubble {
  max-width: 70%;
  padding: 10px 15px;
  position: relative;
  background: white;
  color: #2e2d2e;
  border-radius: 4px 20px 20px 20px;
  align-self: flex-start;
  box-sizing: border-box;
}

.chat-bubble::before {
  content: none;
  /* 移除三角箭头 */
}

.chat-item-user {
  justify-content: flex-end;
  /* 修改为 flex-end */
}

.chat-item-user .chat-avatar {
  margin-left: 10px;
  /* 移动到右侧 */
  margin-right: 0;
}

.chat-item-user .chat-bubble {
  background: linear-gradient(270deg,
      rgb(182, 119, 255) 4.327%,
      rgb(25, 85, 247) 92.788%);
  color: white;
  border-radius: 20px 4px 20px 20px;
  /* 更新 border-radius */
  align-self: flex-end;
  box-sizing: border-box;
  /* 修改为 flex-end */
}

.chat-item-bot {
  justify-content: flex-start;
}

.chat-item-bot .chat-bubble {
  background: white;
  color: #2e2d2e;
  border-radius: 4px 20px 20px 20px;
  /* 保持和伪元素逻辑一致 */
  align-self: flex-start;
  box-sizing: border-box;
  position: relative;
  overflow: hidden;
  border: 2px solid transparent;
}

.chat-item-bot.processing .chat-bubble {
  border: 2px solid transparent;
  min-width: 163px;
  animation: borderAnimation 3s infinite;
}

@keyframes borderAnimation {
  0% {
    border-color: #1955f7;
  }

  20% {
    border-color: #b677ff;
  }

  40% {
    border-color: #1955f7;
  }

  60% {
    border-color: #b677ff;
  }

  80% {
    border-color: #1955f7;
  }

  100% {
    border-color: #b677ff;
  }
}

/* 添加自定义样式 */
.processing-text {
  display: inline-block;
}

.processing-text::after {
  content: '...';
  display: inline-block;
  margin-left: 4px;
  animation: dots 1.5s steps(5, end) infinite;
}

@keyframes dots {

  0%,
  20% {
    content: '.';
  }

  40% {
    content: '..';
  }

  60% {
    content: '...';
  }

  80%,
  100% {
    content: '';
  }
}

.input-container {
  width: fit-content;
  position: relative;
  margin: 0 auto;
}

.input-field {
  width: 1140px;
  min-height: 120px;
  padding: 15px 46px 15px 15px;
  border: 1px solid #cccccc;
  border-radius: 8px;
  font-size: 14px;
  outline: none;
  box-shadow: 0px 4px 10px 0px rgba(25, 85, 247, 0.15);
  transition: border-color 0.3s;
  resize: vertical;
}

.input-field:focus {
  border-color: rgb(25, 85, 247);
}

.input-button {
  position: absolute;
  right: 17px;
  bottom: 17px;
  background: none;
  border: none;
  cursor: pointer;
  width: 54px;
  border-radius: 100px;
  height: 40px;
  background: rgba(25, 85, 247, 0.4);
  display: flex;
  align-items: center;
  justify-content: center;
}

.input-button.active {
  background: linear-gradient(90deg,
      rgb(182, 119, 255) 3.704%,
      rgb(25, 85, 247) 100%);
}

.input-icon {
  width: 20px;
  height: 20px;
  fill: #7d7d7d;
}

.input-field:disabled {
  background-color: #f0f0f0;
  cursor: not-allowed;
}

.input-button:disabled .input-icon {
  fill: #ccc;
  cursor: not-allowed;
}
</style>
